package com.hh.system.task;

import java.io.File;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.TimerTask;

import org.apache.log4j.Logger;

import com.hh.baseframework.service.impl.BeanFactoryHelper;
import com.hh.baseframework.util.Convert;
import com.hh.baseframework.util.FileUtil;
import com.hh.baseframework.util.statics.StaticVar;
import com.hh.system.service.impl.HibernateService;

public class FileCopyDeleteTask extends TimerTask {
	private static final Logger logger = Logger
			.getLogger(FileCopyDeleteTask.class);
	private HibernateService service = BeanFactoryHelper.getBeanFactory()
			.getBean(HibernateService.class);
	@Override
	public void run() {
		// File file = new File(StaticVar.filepath + "/task");

		// String filePath =
		// "E:/green/apache-tomcat-7.0.26/wtpwebapps/uploadfile/" + "task/";

		String filePath = (StaticVar.filepath + "/task/").replaceAll("//", "/");
		File file = new File(filePath);
		List<String> allFilePathList = new ArrayList<String>();
		showAllFiles(file, allFilePathList);
		for (String path : allFilePathList) {
			String path2 = path.replaceAll("\\\\", "/").replace(filePath, "");
			String[] pathArr = path2.split("/");
			String[] tableNames = pathArr[0].split("#");
			String column = pathArr[1];
			
			boolean as =true;
			for (String tableName : tableNames) {
				String sql = "select count(*) from " + tableName + " where "
						+ column + " like " + "'%"
						+ pathArr[pathArr.length - 1] + "%'";
				BigInteger count = (BigInteger) service.findObjectBySql(sql);
				if (count.intValue()>0) {
					as=false;
					break;
				}
			}
			
			
			if (as) {
				String createBasePath=StaticVar.filepath + "/deletebak/";
				List<String> createFileList = new ArrayList<String>();
				createFileList.add(createBasePath);
				
				for (int i = 0; i < pathArr.length-1; i++) {
					createBasePath+="/"+pathArr[i];
					createFileList.add(createBasePath);
				}
				FileUtil.isExist(createFileList);
				String newpath = StaticVar.filepath + "/deletebak/" + path2;
				FileUtil.moveFile(path, newpath);
			}

		}

	}

	final static void showAllFiles(File dir, List<String> allFilePathList) {
		File[] fs = dir.listFiles();
		for (int i = 0; i < fs.length; i++) {
			if (fs[i].isDirectory()) {
				try {
					showAllFiles(fs[i], allFilePathList);
				} catch (Exception e) {
					logger.error("遍历附件文件夹出错！" + e.getClass().getName() + "："
							+ e.getMessage());
				}
			} else {
				allFilePathList.add(fs[i].getAbsolutePath());
			}
		}
	}

}
